<script setup>
import { ref, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Plus, Edit, Delete, Lock, Unlock, Share, MoreFilled } from '@element-plus/icons-vue'
import KnowledgeManage from '@/components/KnowledgeManage.vue'
import { getRolePresetList, createRolePreset, updateRolePreset, deleteRolePreset } from '@/api/rolePreset.js'
import AvatarSelection from "@/components/AvatarSelection.vue";

// 角色列表
const roleList = ref([])
const loading = ref(false)

// 搜索相关
const searchQuery = ref('')

// 分页相关
const currentPage = ref(1)
const pageSize = ref(12) // 每页显示12个角色
const total = ref(0)

// 新增/编辑角色弹窗相关
const dialogVisible = ref(false)
const dialogTitle = ref('新增角色')
const isEdit = ref(false)
const currentRole = ref(null)

const showKnowledgeDialog = ref(false)
const selectedRoleForKnowledge = ref(null)

// 管理知识库
const manageKnowledge = (role) => {
  selectedRoleForKnowledge.value = role
  showKnowledgeDialog.value = true
}

// 切换角色公开/私有状态
const toggleRolePrivacy = async (role) => {
  try {
    const newPrivateStatus = role.isPrivate === 0 ? 1 : 0 // 0私有->1公开，1公开->0私有
    const statusText = newPrivateStatus === 0 ? '私有' : '公开'

    await ElMessageBox.confirm(
      `确定要将角色 "${role.roleName}" 设置为${statusText}吗？`,
      '状态切换确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )

    const updateData = {
      ...role,
      isPrivate: newPrivateStatus,
      tags: typeof role.tags === 'string' ? role.tags : JSON.stringify(role.tags || [])
    }

    const res = await updateRolePreset(updateData)
    if (res.code === 200) {
      ElMessage.success(`角色已设置为${statusText}`)
      fetchRoleList() // 重新获取列表
    } else {
      ElMessage.error(res.msg || '状态切换失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('切换角色状态失败:', error)
      ElMessage.error('状态切换失败，请稍后重试')
    }
  }
}

// 表单验证规则
const rules = {
  roleName: [
    { required: true, message: '请输入角色名称', trigger: 'blur' },
    { min: 1, max: 50, message: '角色名称长度在 1 到 50 个字符', trigger: 'blur' }
  ],
  roleDescription: [
    { required: true, message: '请输入角色描述', trigger: 'blur' },
    { min: 1, max: 200, message: '角色描述长度在 1 到 200 个字符', trigger: 'blur' }
  ],
  systemPrompt: [
    { required: true, message: '请输入系统提示词', trigger: 'blur' },
    { min: 1, max: 1000, message: '系统提示词长度在 1 到 1000 个字符', trigger: 'blur' }
  ],
  avatarUrl: [
    { required: true, message: '请上传头像', trigger: 'blur' },
  ],
}

// 角色表单数据
const roleForm = ref({
  id: null,
  roleName: '',
  roleDescription: '',
  systemPrompt: '',
  avatarUrl: '',
  tags: [],
  isPrivate: 0 // 默认私有
})

// 标签输入
const tagInput = ref('')
const inputVisible = ref(false)

// 获取角色列表 - 修改为支持分页
const fetchRoleList = async (page = 1, roleName = '') => {
  loading.value = true
  try {
    const params = {
      startPage: page,
      pageSize: pageSize.value,
      isPrivate: 0 // 查询私有角色 (0代表私有)
    }

    // 添加搜索条件
    if (roleName) {
      params.roleName = roleName
    }

    console.log('请求参数:', params) // 调试日志

    const res = await getRolePresetList(params)
    console.log('后端返回数据:', res) // 调试日志

    if (res.code === 200) {
      // 根据后端实际返回的数据结构调整
      if (res.data && typeof res.data === 'object' && res.data.records) {
        // MyBatis-Plus分页结构
        roleList.value = res.data.records || []
        total.value = res.data.total || 0
        currentPage.value = res.data.current || page
      } else if (Array.isArray(res.data)) {
        // 如果返回的是数组，说明没有分页
        roleList.value = res.data
        total.value = res.data.length
        currentPage.value = page
      } else {
        // 其他情况
        roleList.value = []
        total.value = 0
        currentPage.value = 1
      }
    } else {
      ElMessage.error(res.msg || '获取角色列表失败')
      roleList.value = []
      total.value = 0
    }
  } catch (error) {
    console.error('获取角色列表出错:', error)
    ElMessage.error('获取角色列表失败，请稍后重试')
    roleList.value = []
    total.value = 0
  } finally {
    loading.value = false
  }
}

// 解析标签字符串为数组
const parseTags = (tagsStr) => {
  try {
    return JSON.parse(tagsStr || '[]')
  } catch (error) {
    return []
  }
}

// 搜索角色
const searchRoles = () => {
  currentPage.value = 1 // 搜索时重置到第一页
  fetchRoleList(1, searchQuery.value.trim())
}

// 清空搜索
const clearSearch = () => {
  searchQuery.value = ''
  currentPage.value = 1
  fetchRoleList(1)
}

// 处理回车键搜索
const handleEnterSearch = () => {
  searchRoles()
}

// 分页改变事件
const handlePageChange = (page) => {
  console.log('页码改变:', page) // 调试日志
  currentPage.value = page
  fetchRoleList(page, searchQuery.value.trim())
}

// 每页大小改变事件
const handleSizeChange = (size) => {
  console.log('每页大小改变:', size) // 调试日志
  pageSize.value = size
  currentPage.value = 1
  fetchRoleList(1, searchQuery.value.trim())
}

// 根据创建时间排序的角色列表
const sortedRoleList = computed(() => {
  return [...roleList.value].sort((a, b) => new Date(b.createTime) - new Date(a.createTime))
})

// 打开新增角色对话框
const openAddDialog = () => {
  isEdit.value = false
  dialogTitle.value = '新增角色'
  roleForm.value = {
    id: null,
    roleName: '',
    roleDescription: '',
    systemPrompt: '',
    avatarUrl: '',
    tags: [],
    isPrivate: 0 // 默认私有
  }
  dialogVisible.value = true
}

// 打开编辑角色对话框
const openEditDialog = (role) => {
  isEdit.value = true
  dialogTitle.value = '编辑角色'
  currentRole.value = role
  roleForm.value = {
    id: role.id,
    roleName: role.roleName,
    roleDescription: role.roleDescription,
    systemPrompt: role.systemPrompt,
    avatarUrl: role.avatarUrl,
    tags: parseTags(role.tags), // 使用parseTags解析标签
    isPrivate: role.isPrivate // 保持原有的isPrivate值
  }
  dialogVisible.value = true
}

// 删除角色
const deleteRole = async (roleId) => {
  try {
    const role = roleList.value.find(r => r.id === roleId)
    await ElMessageBox.confirm(
      `确定要删除角色 "${role?.roleName}" 吗？`,
      '删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )

    const res = await deleteRolePreset(roleId)
    if (res.code === 200) {
      ElMessage.success('删除成功')
      fetchRoleList() // 重新获取列表
    } else {
      ElMessage.error(res.msg || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除角色失败:', error)
      ElMessage.error('删除失败，请稍后重试')
    }
  }
}

// 保存角色
const saveRole = async () => {
  if (!roleForm.value.roleName.trim()) {
    ElMessage.warning('请输入角色名称')
    return
  }
  if (!roleForm.value.roleDescription.trim()) {
    ElMessage.warning('请输入角色描述')
    return
  }
  if (!roleForm.value.systemPrompt.trim()) {
    ElMessage.warning('请输入系统提示词')
    return
  }
  if (!roleForm.value.avatarUrl.trim()) {
    ElMessage.warning('请上传头像')
    return
  }

  try {
    // 准备提交的数据
    const submitData = {
      ...roleForm.value,
      tags: JSON.stringify(roleForm.value.tags), // 将标签数组转换为JSON字符串
      isPrivate: roleForm.value.isPrivate // 确保isPrivate值正确传递
    }

    let res
    if (isEdit.value) {
      // 编辑模式
      res = await updateRolePreset(submitData)
      if (res.code === 200) {
        ElMessage.success('编辑成功')
      } else {
        ElMessage.error(res.msg || '编辑失败')
        return
      }
    } else {
      // 新增模式
      delete submitData.id // 新增时不需要id
      res = await createRolePreset(submitData)
      if (res.code === 200) {
        ElMessage.success('新增成功')
      } else {
        ElMessage.error(res.msg || '新增失败')
        return
      }
    }

    dialogVisible.value = false
    fetchRoleList() // 重新获取角色列表
  } catch (error) {
    console.error('保存失败:', error)
    ElMessage.error('保存失败，请稍后重试')
  }
}

// 添加标签
const addTag = () => {
  if (tagInput.value && !roleForm.value.tags.includes(tagInput.value)) {
    roleForm.value.tags.push(tagInput.value)
    tagInput.value = ''
  }
  inputVisible.value = false
}

// 删除标签
const removeTag = (tag) => {
  const index = roleForm.value.tags.indexOf(tag)
  if (index > -1) {
    roleForm.value.tags.splice(index, 1)
  }
}

// 显示标签输入框
const showTagInput = () => {
  inputVisible.value = true
}

const avatarSelectionVisible = ref(false)

// 显示头像选择对话框
const showAvatarSelection = () => {
  avatarSelectionVisible.value = true
}

// 处理头像选择结果
const handleAvatarSelected = (avatarUrl) => {
  roleForm.value.avatarUrl = avatarUrl
}

// 分享角色功能
const shareRole = async (role) => {
  try {
    // 只有公开角色才能分享（isPrivate === 1 表示私有，0 表示公开）
    console.log('分享角色:', role)
    if (role.isPrivate === 0) {
      ElMessage.warning('只有公开角色才能分享')
      return
    }

    // 生成分享链接
    const baseUrl = window.location.origin
    const shareUrl = `${baseUrl}/#/role-square?shared=${role.id}`
    
    // 复制到剪贴板
    await navigator.clipboard.writeText(shareUrl)
    
    ElMessage.success('分享链接已复制到剪贴板！')
  } catch (error) {
    console.error('复制分享链接失败:', error)
    
    // 如果剪贴板API不可用，使用备用方法
    try {
      const textArea = document.createElement('textarea')
      const baseUrl = window.location.origin
      const shareUrl = `${baseUrl}/#/role-square?shared=${role.id}`
      textArea.value = shareUrl
      document.body.appendChild(textArea)
      textArea.select()
      document.execCommand('copy')
      document.body.removeChild(textArea)
      ElMessage.success('分享链接已复制到剪贴板！')
    } catch (fallbackError) {
      console.error('备用复制方法也失败:', fallbackError)
      ElMessage.error('复制失败，请手动复制链接')
    }
  }
}

onMounted(() => {
  fetchRoleList()
})
</script>

<template>
  <div class="role-preset-manage">
    <!-- 上半部分：标题、新增按钮和搜索栏 -->
    <div class="manage-header">
      <div class="header-top">
        <h1>个人角色管理</h1>
        <el-button type="primary" :icon="Plus" @click="openAddDialog">
          新增角色
        </el-button>
      </div>

      <!-- 搜索框 -->
      <div class="search-container">
        <div class="search-wrapper">
          <el-input v-model="searchQuery" placeholder="搜索角色名称..." class="search-input" clearable @clear="clearSearch"
            @keyup.enter="handleEnterSearch">
            <template #prefix>
              <el-icon>
                <Search />
              </el-icon>
            </template>
          </el-input>
          <el-button type="primary" @click="searchRoles" :loading="loading" icon="Search" class="search-button">
            搜索
          </el-button>
        </div>
      </div>
    </div>

    <!-- 下半部分：角色信息展示 -->
    <div class="role-content">
      <el-row :gutter="16" class="role-list" v-loading="loading">
        <el-col :xs="24" :sm="12" :md="8" :lg="6" v-for="role in sortedRoleList" :key="role.id" class="role-col">
          <el-card class="role-card" shadow="hover">
            <div class="role-avatar">
              <el-avatar :size="80" :src="role.avatarUrl" />
            </div>
            <div class="role-info">
              <h3 class="role-name">{{ role.roleName }}</h3>
              <div class="usage-info">
                <span class="usage-count">使用 {{ role.usageCount }} 次</span>
                <span class="create-time">{{ role.createTime }}</span>
              </div>
              <p class="role-description">{{ role.roleDescription }}</p>
              <div class="role-tags">
                <el-tag v-for="(tag, index) in parseTags(role.tags)" :key="index" size="small" class="role-tag">
                  {{ tag }}
                </el-tag>
              </div>
              <!-- 优化后的按钮布局 -->
              <div class="role-actions">
                <div class="main-actions">
                  <el-button size="small" type="primary" @click="openEditDialog(role)" :icon="Edit">
                    编辑
                  </el-button>
                  <el-button size="small" type="success" @click="manageKnowledge(role)">
                    知识库
                  </el-button>
                  <el-button size="small" :type="role.isPrivate === 0 ? 'warning' : 'info'"
                    :icon="role.isPrivate === 0 ? Lock : Unlock" @click="toggleRolePrivacy(role)">
                    {{ role.isPrivate === 0 ? '私有' : '公开' }}
                  </el-button>
                </div>
                <div class="more-actions">
                  <el-dropdown trigger="click" placement="bottom-end">
                    <el-button size="small" type="default" :icon="MoreFilled" circle />
                    <template #dropdown>
                      <el-dropdown-menu>
                        <el-dropdown-item @click="shareRole(role)" :disabled="role.isPrivate === 0">
                          <el-icon><Share /></el-icon>
                          分享角色
                        </el-dropdown-item>
                        <el-dropdown-item @click="deleteRole(role.id)" divided>
                          <el-icon><Delete /></el-icon>
                          <span style="color: var(--el-color-danger)">删除角色</span>
                        </el-dropdown-item>
                      </el-dropdown-menu>
                    </template>
                  </el-dropdown>
                </div>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>

      <div v-if="roleList.length === 0 && !loading" class="no-data">
        <el-empty :description="searchQuery ? '未找到匹配的角色' : '暂无角色数据'" />
      </div>
    </div>

    <!-- 美化的分页组件 -->
    <div class="pagination-container" v-if="total > 0">
      <div class="pagination-main">
        <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[8, 12, 16, 24]"
          :total="total" layout="prev, pager, next" :pager-count="5" @size-change="handleSizeChange"
          @current-change="handlePageChange" class="custom-pagination" background small />
      </div>
      <div class="pagination-info">
        <span class="total-info">共 {{ total }} 条</span>
        <el-select v-model="pageSize" @change="handleSizeChange" size="small" class="size-select">
          <el-option label="8条/页" :value="8" />
          <el-option label="12条/页" :value="12" />
          <el-option label="16条/页" :value="16" />
          <el-option label="24条/页" :value="24" />
        </el-select>
      </div>
    </div>

    <!-- 新增/编辑角色弹窗 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="600px" :close-on-click-modal="false"
      class="role-dialog">
      <el-form :model="roleForm" label-width="100px" class="role-form" :rules="rules">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="roleForm.roleName" placeholder="请输入角色名称" />
        </el-form-item>

        <el-form-item label="角色描述" prop="roleDescription">
          <el-input v-model="roleForm.roleDescription" type="textarea" :rows="3" placeholder="请输入角色描述" />
        </el-form-item>

        <el-form-item label="系统提示词" prop="systemPrompt">
          <el-input v-model="roleForm.systemPrompt" type="textarea" :rows="5" placeholder="请输入系统提示词" />
        </el-form-item>

        <el-form-item label="头像" prop="avatarUrl">
          <el-tooltip
              class="box-item"
              effect="dark"
              content="点击更换头像"
              placement="top"
          >
            <el-avatar
                :src="roleForm.avatarUrl"
                @click="showAvatarSelection"
                style="cursor: pointer;"
                size="large"
            />
            <el-input v-model="roleForm.avatarUrl" type="hidden"></el-input>
          </el-tooltip>
        </el-form-item>

        <el-form-item label="角色标签">
          <div class="tags-container">
            <el-tag v-for="tag in roleForm.tags" :key="tag" closable @close="removeTag(tag)" class="tag-item">
              {{ tag }}
            </el-tag>
            <el-input v-if="inputVisible" ref="tagInputRef" v-model="tagInput" size="small" class="tag-input"
              @keyup.enter="addTag" @blur="addTag" />
            <el-button v-else size="small" @click="showTagInput">+ 添加标签</el-button>
          </div>
        </el-form-item>

        <el-form-item label="角色状态">
          <el-radio-group v-model="roleForm.isPrivate">
            <el-radio :label="0">私有</el-radio>
            <el-radio :label="1">公开</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveRole">保存</el-button>
        </div>
      </template>
    </el-dialog>
  </div>

  <AvatarSelection
      v-model="avatarSelectionVisible"
      :current-avatar="roleForm.avatarUrl"
      @avatar-selected="handleAvatarSelected"
  />

  <!-- 知识库管理弹窗 -->
  <el-dialog v-model="showKnowledgeDialog" title="知识库管理" width="80%" top="5vh" class="knowledge-dialog">
    <KnowledgeManage :selected-role="selectedRoleForKnowledge" />
  </el-dialog>
</template>

<style scoped>
.role-preset-manage {
  display: flex;
  flex-direction: column;
  height: 100%;
  background-color: var(--el-bg-color);
}

.manage-header {
  margin: 20px;
  padding: 20px;
  border-bottom: 1px solid var(--el-border-color-light);
  display: flex;
  flex-direction: column;
  align-items: center;
}

.header-top {
  display: flex;
  justify-content: flex-start;
  align-items: center;
  margin-bottom: 20px;
  width: 100%;
  position: relative;
}

.header-top h1 {
  font-size: 28px;
  color: var(--el-text-color-primary);
  margin: 0;
  position: absolute;
  left: 50%;
  transform: translateX(-50%);
}

.search-container {
  max-width: 400px;
  width: 100%;
  display: flex;
  justify-content: center;
}

.search-wrapper {
  display: flex;
  gap: 8px;
  align-items: center;
  width: 100%;
}

.search-input {
  flex: 1;
}

.search-button {
  flex-shrink: 0;
  height: 32px;
  padding: 0 16px;
}

.role-content {
  flex: 1;
  overflow-y: auto;
  overflow-x: hidden;
  margin-bottom: 10px;
  padding: 0 12px;
  min-height: 0;
}

.role-list {
  margin: 0 -8px;
  display: flex;
  flex-wrap: wrap;
}

.role-col {
  margin-bottom: 16px;
  padding: 0 8px;
  display: flex;
}

.role-card {
  width: 100%;
  border-radius: 12px;
  transition: all 0.3s ease;
  border: 1px solid var(--el-border-color-lighter);
  display: flex;
  flex-direction: column;
  height: 420px; /* 固定高度确保一致性 */
}

.role-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.1);
}

:deep(.role-card .el-card__body) {
  padding: 20px;
  display: flex;
  flex-direction: column;
  height: 100%;
}

.role-avatar {
  text-align: center;
  margin-bottom: 16px;
  flex-shrink: 0;
}

.role-info {
  display: flex;
  flex-direction: column;
  flex: 1;
  min-height: 0;
}

.role-name {
  font-size: 18px;
  font-weight: 600;
  color: var(--el-text-color-primary);
  margin: 0 0 8px 0;
  text-align: center;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  flex-shrink: 0;
}

.usage-info {
  display: flex;
  justify-content: space-between;
  font-size: 12px;
  color: var(--el-text-color-regular);
  margin-bottom: 12px;
  flex-shrink: 0;
}

.role-description {
  font-size: 14px;
  color: var(--el-text-color-regular);
  margin: 0 0 12px 0;
  line-height: 1.4;
  display: -webkit-box;
  -webkit-line-clamp: 3;
  -webkit-box-orient: vertical;
  overflow: hidden;
  text-overflow: ellipsis;
  flex: 1;
  min-height: 60px; /* 确保描述区域有最小高度 */
}

.role-tags {
  margin-bottom: 16px;
  display: flex;
  flex-wrap: wrap;
  gap: 4px;
  min-height: 24px; /* 确保标签区域有最小高度 */
  flex-shrink: 0;
}

.role-tag {
  font-size: 12px;
}

/* 优化后的按钮布局样式 - 确保按钮在底部 */
.role-actions {
  margin-top: auto; /* 关键：将按钮推到底部 */
  display: flex;
  align-items: center;
  gap: 8px;
  flex-shrink: 0;
  padding-top: 8px;
  border-top: 1px solid var(--el-border-color-lighter);
}

.main-actions {
  flex: 1;
  display: flex;
  gap: 6px;
}

.main-actions .el-button {
  flex: 1;
  font-size: 12px;
  padding: 6px 8px;
  min-width: 0;
}

.more-actions {
  flex-shrink: 0;
}

.more-actions .el-button {
  width: 28px;
  height: 28px;
  padding: 0;
}

/* 下拉菜单样式优化 */
:deep(.el-dropdown-menu__item) {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 8px 16px;
}

:deep(.el-dropdown-menu__item:hover) {
  background-color: var(--el-fill-color-light);
}

:deep(.el-dropdown-menu__item.is-divided) {
  border-top: 1px solid var(--el-border-color-lighter);
}

/* 自定义滚动条样式 */
.role-content::-webkit-scrollbar {
  width: 6px;
}

.role-content::-webkit-scrollbar-track {
  background: var(--el-fill-color-lighter);
  border-radius: 3px;
}

.role-content::-webkit-scrollbar-thumb {
  background: var(--el-border-color-darker);
  border-radius: 3px;
}

.role-content::-webkit-scrollbar-thumb:hover {
  background: var(--el-border-color-dark);
}

/* 美化分页样式 */
.pagination-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 12px;
  padding: 16px;
  flex-shrink: 0;
  background: var(--el-bg-color);
  border-top: 1px solid var(--el-border-color-light);
  margin-top: 10px;
  width: 100%;
  box-sizing: border-box;
  overflow-x: hidden;
  overflow-y: visible;
}

.pagination-main {
  width: 100%;
  display: flex;
  justify-content: center;
  overflow-x: hidden;
  overflow-y: visible;
}

.custom-pagination {
  --el-pagination-bg-color: var(--el-bg-color);
  --el-pagination-text-color: var(--el-text-color-primary);
  --el-pagination-border-radius: 6px;
  width: 100%;
  max-width: 100%;
  overflow-x: hidden;
  overflow-y: visible;
}

.pagination-info {
  display: flex;
  align-items: center;
  gap: 12px;
  font-size: 14px;
  flex-wrap: wrap;
  justify-content: center;
  width: 100%;
  max-width: 100%;
}

.total-info {
  color: var(--el-text-color-regular);
  white-space: nowrap;
  font-size: 13px;
}

.size-select {
  width: 90px;
  flex-shrink: 0;
}

/* 自定义分页按钮样式 */
:deep(.custom-pagination) {
  display: flex !important;
  align-items: center !important;
  justify-content: center !important;
  width: 100% !important;
  max-width: 100% !important;
  overflow-x: hidden !important;
  overflow-y: visible !important;
  gap: 4px !important;
}

:deep(.custom-pagination .el-pagination__total),
:deep(.custom-pagination .el-pagination__sizes),
:deep(.custom-pagination .el-pagination__jump) {
  display: none !important;
}

:deep(.custom-pagination .el-pager) {
  display: flex !important;
  align-items: center !important;
  justify-content: center !important;
  gap: 4px !important;
  margin: 0 !important;
  flex: 0 0 auto !important;
  overflow: hidden !important;
}

:deep(.custom-pagination .el-pager li) {
  background: var(--el-fill-color-light) !important;
  border: 1px solid var(--el-border-color-lighter) !important;
  border-radius: 4px !important;
  margin: 0 !important;
  transition: all 0.3s ease !important;
  width: 24px !important;
  min-width: 24px !important;
  max-width: 24px !important;
  height: 24px !important;
  display: flex !important;
  align-items: center !important;
  justify-content: center !important;
  font-size: 12px !important;
  flex-shrink: 0 !important;
}

:deep(.custom-pagination .el-pager li:hover) {
  background: var(--el-color-primary-light-9) !important;
  border-color: var(--el-color-primary-light-7) !important;
  color: var(--el-color-primary) !important;
}

:deep(.custom-pagination .el-pager li.is-active) {
  background: var(--el-color-primary) !important;
  border-color: var(--el-color-primary) !important;
  color: #fff !important;
  font-weight: 600 !important;
}

:deep(.custom-pagination .btn-prev),
:deep(.custom-pagination .btn-next) {
  background: var(--el-fill-color-light) !important;
  border: 1px solid var(--el-border-color-lighter) !important;
  border-radius: 4px !important;
  transition: all 0.3s ease !important;
  width: 24px !important;
  min-width: 24px !important;
  max-width: 24px !important;
  height: 24px !important;
  display: flex !important;
  align-items: center !important;
  justify-content: center !important;
  flex-shrink: 0 !important;
  font-size: 12px !important;
  margin: 0 !important;
}

:deep(.custom-pagination .btn-prev:hover),
:deep(.custom-pagination .btn-next:hover) {
  background: var(--el-color-primary-light-9) !important;
  border-color: var(--el-color-primary-light-7) !important;
  color: var(--el-color-primary) !important;
}

:deep(.custom-pagination .btn-prev:disabled),
:deep(.custom-pagination .btn-next:disabled) {
  background: var(--el-fill-color-lighter) !important;
  border-color: var(--el-border-color-light) !important;
  color: var(--el-text-color-disabled) !important;
  cursor: not-allowed !important;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .role-preset-manage {
    padding: 15px;
  }

  .role-card {
    height: auto; /* 小屏幕上允许自适应高度 */
    min-height: 380px; /* 但保持最小高度 */
  }

  .pagination-container {
    padding: 12px 8px;
    gap: 8px;
  }

  .pagination-info {
    flex-direction: column;
    gap: 6px;
  }

  .size-select {
    width: 100px;
  }

  :deep(.custom-pagination) {
    gap: 3px !important;
  }

  :deep(.custom-pagination .el-pager) {
    gap: 3px !important;
  }

  :deep(.custom-pagination .el-pager li) {
    width: 20px !important;
    min-width: 20px !important;
    max-width: 20px !important;
    height: 20px !important;
    font-size: 11px !important;
  }

  :deep(.custom-pagination .btn-prev),
  :deep(.custom-pagination .btn-next) {
    width: 20px !important;
    min-width: 20px !important;
    max-width: 20px !important;
    height: 20px !important;
    font-size: 11px !important;
  }

  .main-actions {
    flex-direction: column;
    gap: 4px;
  }

  .main-actions .el-button {
    flex: none;
    width: 100%;
  }

  .role-actions {
    flex-direction: column;
    align-items: stretch;
    gap: 8px;
  }

  .more-actions {
    align-self: center;
  }
}

@media (max-width: 480px) {
  .role-card {
    min-height: 350px;
  }

  .pagination-container {
    padding: 10px 6px;
  }

  :deep(.custom-pagination) {
    gap: 2px !important;
  }

  :deep(.custom-pagination .el-pager) {
    gap: 2px !important;
  }

  :deep(.custom-pagination .el-pager li) {
    width: 18px !important;
    min-width: 18px !important;
    max-width: 18px !important;
    height: 18px !important;
    font-size: 10px !important;
  }

  :deep(.custom-pagination .btn-prev),
  :deep(.custom-pagination .btn-next) {
    width: 18px !important;
    min-width: 18px !important;
    max-width: 18px !important;
    height: 18px !important;
    font-size: 10px !important;
  }
}

/* 对话框样式 */
.role-dialog {
  border-radius: 12px;
}

.role-form {
  padding: 20px 0;
}

.tags-container {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  align-items: center;
}

.tag-item {
  margin: 0;
}

.tag-input {
  width: 100px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

.no-data {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 200px;
}

/* 知识库弹窗样式 */
.knowledge-dialog {
  border-radius: 12px;
}

:deep(.knowledge-dialog .el-dialog) {
  border-radius: 12px;
  box-shadow: 0 12px 32px rgba(0, 0, 0, 0.1);
}

:deep(.knowledge-dialog .el-dialog__header) {
  padding: 24px 24px 16px;
  border-bottom: 1px solid var(--el-border-color-lighter);
  background: linear-gradient(135deg, var(--el-color-primary-light-9) 0%, var(--el-fill-color-extra-light) 100%);
}

:deep(.knowledge-dialog .el-dialog__title) {
  font-size: 18px;
  font-weight: 600;
  color: var(--el-text-color-primary);
}

:deep(.knowledge-dialog .el-dialog__body) {
  padding: 24px;
  max-height: 70vh;
  overflow-y: auto;
}

/* 知识库组件内部样式优化 */
:deep(.knowledge-manage) {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

:deep(.knowledge-header) {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 20px;
  background: var(--el-fill-color-extra-light);
  border-radius: 8px;
  border: 1px solid var(--el-border-color-lighter);
}

:deep(.knowledge-header h3) {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
  color: var(--el-text-color-primary);
}

:deep(.search-section) {
  margin: 0;
}

:deep(.knowledge-list) {
  display: flex;
  flex-direction: column;
  gap: 16px;
  max-height: 400px;
  overflow-y: auto;
  padding-right: 8px;
}

:deep(.knowledge-item) {
  border-radius: 8px;
  border: 1px solid var(--el-border-color-lighter);
  transition: all 0.3s ease;
}

:deep(.knowledge-item:hover) {
  border-color: var(--el-color-primary-light-7);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
}

:deep(.knowledge-item .el-card__body) {
  padding: 20px;
}

:deep(.doc-header) {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 12px;
  gap: 16px;
}

:deep(.doc-header h4) {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
  color: var(--el-text-color-primary);
  flex: 1;
  line-height: 1.4;
}

:deep(.doc-actions) {
  display: flex;
  align-items: center;
  gap: 8px;
  flex-shrink: 0;
}

:deep(.doc-content) {
  margin: 0 0 16px 0;
  font-size: 14px;
  color: var(--el-text-color-regular);
  line-height: 1.6;
  background: var(--el-fill-color-extra-light);
  padding: 12px 16px;
  border-radius: 6px;
  border-left: 3px solid var(--el-color-primary-light-7);
}

:deep(.doc-meta) {
  display: flex;
  justify-content: space-between;
  font-size: 12px;
  color: var(--el-text-color-secondary);
  padding-top: 12px;
  border-top: 1px solid var(--el-border-color-lighter);
}

:deep(.doc-meta span) {
  padding: 4px 8px;
  background: var(--el-fill-color-light);
  border-radius: 4px;
}

/* 知识库列表滚动条样式 */
:deep(.knowledge-list::-webkit-scrollbar) {
  width: 6px;
}

:deep(.knowledge-list::-webkit-scrollbar-track) {
  background: var(--el-fill-color-lighter);
  border-radius: 3px;
}

:deep(.knowledge-list::-webkit-scrollbar-thumb) {
  background: var(--el-border-color-darker);
  border-radius: 3px;
}

:deep(.knowledge-list::-webkit-scrollbar-thumb:hover) {
  background: var(--el-border-color-dark);
}

/* 添加知识弹窗样式优化 */
:deep(.knowledge-manage .el-dialog) {
  border-radius: 8px;
}

:deep(.knowledge-manage .el-tabs) {
  margin-top: 16px;
}

:deep(.knowledge-manage .el-tabs__content) {
  padding-top: 20px;
}

:deep(.knowledge-manage .el-form-item) {
  margin-bottom: 20px;
}

:deep(.knowledge-manage .el-upload-dragger) {
  border-radius: 8px;
  border: 2px dashed var(--el-border-color-lighter);
  transition: all 0.3s ease;
}

:deep(.knowledge-manage .el-upload-dragger:hover) {
  border-color: var(--el-color-primary);
  background-color: var(--el-color-primary-light-9);
}

/* 响应式设计 */
@media (max-width: 1200px) {
  :deep(.knowledge-dialog) {
    width: 60% !important;
  }
}

@media (max-width: 768px) {
  :deep(.knowledge-dialog) {
    width: 90% !important;
    margin: 0 5%;
  }
  
  :deep(.knowledge-dialog .el-dialog__body) {
    padding: 16px;
    max-height: 60vh;
  }
  
  :deep(.knowledge-header) {
    flex-direction: column;
    gap: 12px;
    align-items: stretch;
  }
  
  :deep(.doc-header) {
    flex-direction: column;
    gap: 8px;
    align-items: stretch;
  }
  
  :deep(.doc-actions) {
    justify-content: flex-end;
  }
  
  :deep(.doc-meta) {
    flex-direction: column;
    gap: 8px;
  }
}
</style>
